import { Button, Col, Input, Row } from 'antd';
import React, { useEffect, useRef } from 'react';
import './style.css';
import Sortable from 'sortablejs';
import { pickerItems } from './config';
import { eventBus, uniqueKey } from '../../utils';

function Picker() {
    const sortableRef = useRef<Sortable>();
    const wrapRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (wrapRef.current) {
            const keys = [...pickerItems.keys()];

            sortableRef.current = new Sortable(wrapRef.current, {
                group: {
                    name: 'shared',
                    pull: 'clone',
                    put: false
                },
                sort: false,
                chosenClass: 'chosen',
                onEnd: ({ item }) => {
                    const index = +(item.dataset.index || -1);

                    eventBus.emit('push:canvas', {
                        ...pickerItems.get(keys[index]),
                        key: uniqueKey()
                    });
                }
            });
        }
    }, []);

    return (
        <div className="panel-picker" ref={wrapRef}>
            {[...pickerItems.entries()].map(([Control, options], index) => (
                <div data-index={index} key={index}>
                    <h3>{options.formProps.label}</h3>
                    <Control {...options.componentProps} className="control" />
                </div>
            ))}
        </div>
    );
}

export default Picker;
